# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product

import requests
from common.helper import Helper
import json


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "重大疾病保险（含轻重疾）"

    # 生成产品信息
    def genProductInfo(self):

        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(18, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 意外身故/伤残
                "accidentalDie": ["500000"],
                # 个人重大疾病
                "majorDisease": ["200000"],
                # 轻度重大疾病保赔
                "slightDisease": ["60000"],
                # 一般住院津贴
                "generalHospital": ["30/天"],
                # 癌症住院津贴
                "cancerHospital": ["50/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["全面款"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 意外身故/伤残
                "accidentalDie": ["200000"],
                # 个人重大疾病
                "majorDisease": ["200000"],
                # 轻度重大疾病保赔
                "slightDisease": ["60000"],
                # 一般住院津贴
                "generalHospital": ["30/天"],
                # 癌症住院津贴
                "cancerHospital": ["50/天"],
                # 住院手术津贴
                "operationHospital": ["5000"],
                # 产品计划
                "plan": ["热销款"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["expire"], plan[k]["payType"],
                             plan[k]["accidentalDie"], plan[k]["majorDisease"], plan[k]["slightDisease"],
                             plan[k]["generalHospital"], plan[k]["cancerHospital"], plan[k]["operationHospital"],
                             plan[k]["plan"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10]
                ))

    # 执行爬虫
    def requestJson(self, dt=None):
        data = {"planClass": 0, "professionalAmountForm": [
            {"accidentalDie": 500000, "majorDisease": 200000, "slightDisease": 60000, "hospitalAllowance1": 30,
             "hospitalAllowance2": 50, "hospitalAllowance3": 5000},
            {"accidentalDie": 200000, "majorDisease": 200000, "slightDisease": 60000, "hospitalAllowance1": 30,
             "hospitalAllowance2": 50, "hospitalAllowance3": 5000},
            {"accidentalDie": "100000", "majorDisease": "0", "slightDisease": "0", "hospitalAllowance1": "0",
             "hospitalAllowance2": "0", "hospitalAllowance3": "0"}], "beginDate": "2020-03-10",
                "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"]))), "sexCode": dt["gender"]}

        payload = json.dumps(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200:

            if dt["plan"] == "全面款":

                print("~~~~~~~~全面款~~~~~~~~")

                price = (r.json()["quoteResult1"]["originalPremium"])

                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                self.mysql.updatePrice(data)

            else:

                print("~~~~~~~~~热销款~~~~~~~~~")

                price = (r.json()["quoteResult2"]["originalPremium"])

                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                self.mysql.updatePrice(data)

        else:

            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)
            print("\n/*更新产品信息失败:%d*/" % dt["id"])


    def main(self):
        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
